package com.zdy.im.tio.command.handler;


import com.sixeco.framework.core.redis.RedisClusterServer;
import com.sixeco.framework.core.redis.RedisKeys;
import com.sixeco.framework.core.redis.RedisUtil;
import com.github.houbb.sensitive.word.core.SensitiveWordHelper;
import com.sixeco.framework.common.api.ApiDoc;
import com.sixeco.framework.util.ids.GlobalId;
import com.sixeco.framework.util.json.JsonUtils;
import com.zdy.im.chat.ChatMessageBody;
import com.zdy.im.chat.ChatMessageEnum;
import com.zdy.im.chat.ChatMessageInfo;
import com.zdy.im.common.exception.ImException;
import com.zdy.im.conf.ImServerSettings;
import com.zdy.im.core.ICommand;
import com.zdy.im.enums.ImMessageTypeEnum;
import com.zdy.im.tio.TioServerConfig;
import com.zdy.im.tio.command.AbstractCommandHandler;
import com.zdy.im.tio.command.Command;
import com.zdy.im.tio.command.ProtocolManager;
import com.zdy.im.user.dto.request.ImRoomChatMessageRequestDto;
import com.zdy.im.user.dto.response.ImRoomChatMessageResponseDto;
import com.zdy.im.user.service.ImRoomChatMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.core.intf.Packet;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.common.WsResponse;

import java.util.Date;


/**
 * 版本: [1.0]
 * 功能说明: 聊天请求cmd消息命令处理器
 * @Author 作者 : zdy
 * @CreateDate 创建时间: 2021-02-30
 */
@Component
@ApiDoc(module = "WebSocket 项目文档",group = "SOCKET-GROUP")
public class RoomChatRequestHandler extends AbstractCommandHandler {

	@Autowired
	private RedisClusterServer redisClusterServer;


	@Autowired
	private ImServerSettings imServerSettings;

	@Autowired
	private ImRoomChatMessageService imRoomChatMessageService;

	@Override
	public ICommand command() {
		return Command.COMMAND_CHAT_GROUP_REQ;
	}


	public ICommand responseCmd() {
		return Command.COMMAND_CHAT_GROUP_RESP;
	}

	@ApiDoc(
			cmd = "103",methodType = "ws",
			value = "群聊发送协议,协议码cmd=103",
			request = ChatMessageBody.class,
			response = ChatMessageBody.class
	)
	@Override
	public Packet handler(Packet wsPacket, ChannelContext channelContext) throws ImException {
		WsRequest packet = (WsRequest)wsPacket;
		if (packet.getBody() == null) {
			throw new ImException("body is null");
		}
		ChatMessageInfo sendInfo = JsonUtils.parseObject(packet.getWsBodyText(), ChatMessageInfo.class);
		//聊天数据格式不正确
		ChatMessageEnum messageEnum = ChatMessageEnum.getEnum(sendInfo.getType());
		if(sendInfo == null || messageEnum == null){
			Packet respChatPacket = ProtocolManager.ResponsePacket.dataInCorrect(channelContext);
			return respChatPacket;
		}
		ChatMessageBody message = sendInfo.getMessage();
		if(message == null){
			Packet respChatPacket = ProtocolManager.ResponsePacket.dataInCorrect(channelContext);
			return respChatPacket;
		}
		long messageId = message.getMessageId();
		if(messageId == 0){
			message.getSendUserId();
		}
//		String content = SensitiveWordHelper.replace(message.getContent());
		String content = message.getContent();
		message.setMine(false);
		message.setMessageType(message.getMessageType());//消息类型
		message.setServiceTime(new Date());
		message.setGlobalId(GlobalId.get().nextId());
		message.setMessageId(messageId);
		message.setReadStatus(0);//未读
		message.setContent(content);
		message.setType(ImMessageTypeEnum.Group.getKey());//1.用户,0是群


		//todo 保存聊天记录;
		ImRoomChatMessageRequestDto chatRequestDto = ImRoomChatMessageRequestDto.build().clone(message);
		ImRoomChatMessageResponseDto result = imRoomChatMessageService.saveImRoomChatMessage(chatRequestDto);
		if(null == result){
			return ProtocolManager.ResponsePacket.dataToSendFailed(channelContext);
		}
		long groupId = message.getToId();
		//缩放图
		String img = super.getOssImgResize(message.getContentImg(),imServerSettings.getOssResize());
		message.setContentImg(img);
		String messageJson = JsonUtils.toJson(message);
		WsResponse wsResponse = WsResponse.fromText(messageJson, TioServerConfig.CHARSET);
		Tio.sendToGroup(channelContext.tioConfig,String.valueOf(groupId), wsResponse);
		saveRedis(groupId,messageJson);
		return ProtocolManager.ResponsePacket.success(channelContext);


	}

	private void saveRedis(long groupId,String messageJson) {
		String formKey = RedisUtil.formatKey(RedisKeys.MQ_CONSUMER , "roomKey");
		redisClusterServer.hmset(formKey , String.valueOf(groupId), messageJson);

	}


}
